//引入gulp
var gulp = require('gulp');
//引入gulp-babel模块，用于解析es6
var babel = require('gulp-babel');
//引入gulp-uglify模块，用于压缩JS
var uglify = require('gulp-uglify');
//引入gulp-cssnano模块，用于压缩css
var cssnano = require('gulp-cssnano');
//引入gulp-sass模块，用于编译sass
var sass = require('gulp-sass'); 
//引入gulp-autoprefixer模块，用于兼容css
var autoprefixer = require('gulp-autoprefixer');
//引入gulp-connect模块，用于搭建本地临时服务器，实现自动刷新
var connect = require('gulp-connect');
//引入gulp-imagemin模块，用于压缩图片
var imagemin = require('gulp-imagemin')

//定义livereload任务
gulp.task('connect', function () {
    connect.server({
        livereload: true
    });
});

//html任务
gulp.task('html', function(){
    gulp.src('html/*.html')
        .pipe(connect.reload());        
});

//js任务
gulp.task('minjs', function(){
    gulp.src('src/script/*.js')
        .pipe(babel({presets: ['es2015']}))
        .pipe(uglify())
        .pipe(gulp.dest('dist/script'))
        .pipe(connect.reload());        
});

//css任务
gulp.task('mincss', function(){
    gulp.src('src/style/*.css')
        .pipe(sass())  
        .pipe(autoprefixer())
        .pipe(cssnano())
        .pipe(gulp.dest('dist/style'))
        .pipe(connect.reload());
});

// minimages压缩图片任务
gulp.task('minimages', function () {
    gulp.src('src/images/*.*')
        .pipe(imagemin({
             progressive: true
        }))
        .pipe(gulp.dest('dist/images'))
        .pipe(connect.reload());
});

//实时监控代码变化
gulp.task('auto', function(){
    gulp.watch('src/style/*.css', ['mincss']);
    gulp.watch('src/script/*.js', ['minjs']);
    gulp.watch('src/images/*.*', ['minimages']);
    gulp.watch('html/*.html', ['html']);
});

gulp.task('default',['minjs','mincss','minimages','auto','connect']);